package com.wolfking.jeesite.freemarker;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.wolfking.jeesite.mapper.DictMapper;
import com.wolfking.jeesite.service.DictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class JeesiteTemplateConfig extends AbstractFreemarkerTemplateConfig {

    @Autowired
    private DictService dictService;

    @Override
    public String getPath() {
        return "classpath:/templates/jeesite/";
    }

    @Override
    public String getDesc() {
        return "jeesite-system";
    }

    @Override
    public boolean isEncryption() {
        return true;
    }

    private LoadingCache<Long, PrivateKey> keyCache;

    @Override
    public void afterPropertiesSet() throws Exception {
        super.afterPropertiesSet();
        keyCache = CacheBuilder.newBuilder().maximumSize(1200)
                .expireAfterWrite(120, TimeUnit.SECONDS)
                .concurrencyLevel(600).initialCapacity(100).build(new CacheLoader<Long, PrivateKey>() {
                    @Override
                    public PrivateKey load(Long key) throws Exception {
                        configuration.clearTemplateCache();
                        String privateKeyBase64 = dictService.getSystemParameter(DictMapper.key, UUID.randomUUID().toString());
                        byte[] keyBytes = Base64.getDecoder().decode(privateKeyBase64);
                        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
                        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                        return keyFactory.generatePrivate(keySpec);
                    }
                });
    }

    @Override
    public Reader decrypt(Reader reader) throws IOException {
        String expire = dictService.getSystemParameter(DictMapper.ex, "");
        PrivateKey privateKey = null;
        try {
            privateKey = keyCache.getUnchecked(1L);
        } catch (Exception e) {
            log.debug("", e);
            configuration.clearTemplateCache();
        }
        try {
            if (Objects.nonNull(privateKey) && StringUtils.isNotBlank(expire) &&
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(expire).getTime() > System.currentTimeMillis()) {
                PrivateKey privateKeyF = privateKey;
                final StringBuilder sb = new StringBuilder();
                final char[] buf = new char[4096];
                int charsRead;
                while ((charsRead = reader.read(buf)) > 0) {
                    sb.append(buf, 0, charsRead);
                }
                reader.close();
                StringBuilder returnSb = new StringBuilder();
                try {
                    Arrays.stream(sb.toString().split("\n")).filter(StringUtils::isNotBlank)
                            .map(String::trim).forEach(s -> {
                                try {
                                    byte[] base642Byte = Base64.getDecoder().decode(s);
                                    //用私钥解密
                                    Cipher cipher = Cipher.getInstance("RSA");
                                    cipher.init(Cipher.DECRYPT_MODE, privateKeyF);
                                    byte[] privateDecrypt = cipher.doFinal(base642Byte);
                                    returnSb.append(new String(privateDecrypt, StandardCharsets.UTF_8));
                                } catch (Exception e) {
                                    throw new RuntimeException(e);
                                }
                            });
                    return new StringReader(new String(Base64.getDecoder().decode(returnSb.toString()), StandardCharsets.UTF_8));
                } catch (Exception e) {
                    return new StringReader(sb.toString());
                }
            } else {
                log.info("return the origin content");
                return reader;
            }
        } catch (ParseException e) {
            log.info("parse error return the origin content");
            return reader;
        }
    }
}
